import urllib,urllib2,re,xbmcplugin,xbmcgui,os,xbmc,sys,time
__USERAGENT__ = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'

def enum(**enums):
  return type('Enum', (), enums)

def getPath(*rel):
  return xbmc.translatePath(os.path.join(*([os.getcwd()]+list(rel))))
  
def playRtmpFromUrl(s):
  s+="/@@/video/flv_pl"
  playRtmp("rtmp://waflaWBE.walla.co.il/vod/",getMatches(s,"<src>mp4:(.*?)</src>")[0])

def playRtmp(tcUrl,playPath):
  xbmc.Player().play("rtmp://waflaWBE.walla.co.il/ app=vod/  swfvfy=true swfUrl=http://i.walla.co.il/w9/swf/video_swf/vod/walla_vod_player.swf tcurl=rtmp://waflaWBE.walla.co.il/vod/ pageurl=http://walla.co.il/ playpath=mp4:"+playPath)
  
def getMatches(url,pattern,clear=False):
  data = getData(url)
  if (clear):
    data = data.replace("\n","").replace("\t","").replace("\r","")
  
  matches=re.compile(pattern,re.MULTILINE|re.DOTALL).findall(data)
  return matches

def getData(url):
  cachePath = xbmc.translatePath( os.path.join( os.getcwd(), 'cache','pages',urllib.quote(url,"") ))
  if (os.path.exists(cachePath) and (time.time()-os.path.getmtime(cachePath))/60/60 <= 1):
    f = open(cachePath, 'r')
    ret = f.read()
    f.close()
    return ret
  req = urllib2.Request(url)
  req.add_header('User-Agent', __USERAGENT__)
  response = urllib2.urlopen(req)
  data=response.read()
  response.close()
  f = open(cachePath, 'w')
  f.write(data)
  f.close()
  return data
  
def addListItem(module,isFolder,name,url,mode,infoLabels,iconimage,label_2='',thumb=None):
  u=sys.argv[0]+"?module="+module+"&url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
  ok=True
  if (thumb==None):
    thumb=iconimage
  liz=xbmcgui.ListItem(name,label_2,iconimage, thumb)
  liz.setInfo( type="Video", infoLabels=infoLabels )
  ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=isFolder)
  return ok
def addDir(module,name,url,mode,infoLabels,iconimage="DefaultFolder.png"):
   addListItem(module,True,name,url,mode,infoLabels,iconimage)
   
def addVideo(module,name,label2,url,mode,infoLabels,thumb="DefaultVideo.png",iconimage="DefaultVideo.png"):
   addListItem(module,False,name,url,mode,infoLabels,thumb,iconimage)